package com.zf.shuashua.manager;

import android.content.Context;
import android.text.TextUtils;
import android.widget.Toast;

import com.blankj.utilcode.util.AppUtils;
import com.liulishuo.filedownloader.BaseDownloadTask;
import com.liulishuo.filedownloader.FileDownloadListener;
import com.liulishuo.filedownloader.FileDownloader;
import com.liulishuo.filedownloader.util.FileDownloadUtils;

import java.io.File;

/**
 * apk下载安装
 */
public class DownLoadManager {

    private static DownLoadManager instance;

    private DownLoadManager() {

    }

    public static DownLoadManager getInstance() {
        if (null == instance) {
            synchronized (DownLoadManager.class) {
                if (null == instance) {
                    instance = new DownLoadManager();
                }
            }
        }
        return instance;
    }

    public synchronized void startDownload(Context context, String url, String packageName) {
        if(!TextUtils.isEmpty(packageName)){
            if(AppUtils.isAppInstalled(packageName)){
                AppUtils.launchApp(packageName);
                return;
            }
        }
        Toast.makeText(context, "开始下载", Toast.LENGTH_LONG).show();
        FileDownloader.setup(context);
        final String savePath = FileDownloadUtils.getDefaultSaveRootPath() + File.separator;
        FileDownloader.getImpl().create(url).setPath(savePath, true).setListener(new FileDownloadListener() {
            @Override
            protected void pending(BaseDownloadTask task, int soFarBytes, int totalBytes) {
            }

            @Override
            protected void connected(BaseDownloadTask task, String etag, boolean isContinue, int soFarBytes, int totalBytes) {
            }

            @Override
            protected void progress(BaseDownloadTask task, int soFarBytes, int totalBytes) {
            }

            @Override
            protected void blockComplete(BaseDownloadTask task) {
            }

            @Override
            protected void retry(final BaseDownloadTask task, final Throwable ex, final int retryingTimes, final int soFarBytes) {
            }

            @Override
            protected void completed(BaseDownloadTask task) {
//                MLog.logd("下载完成：" + task.getTargetFilePath());
                AppUtils.installApp(task.getTargetFilePath());
            }

            @Override
            protected void paused(BaseDownloadTask task, int soFarBytes, int totalBytes) {
            }

            @Override
            protected void error(BaseDownloadTask task, Throwable e) {
            }

            @Override
            protected void warn(BaseDownloadTask task) {
            }
        }).start();
    }

    public synchronized void startDownload(Context context, String url) {
        startDownload(context, url, "");
    }

}
